<script setup lang="ts">
  import { ref, computed } from 'vue'
  import { ElMenu } from 'element-plus'
  import { StrUtil } from '@xtail/core'
  import { MenuTypeConst } from '../../common'
  import { XSubMenu, SubMenuPropsType } from '../XSubMenu'
  import { XMenuItemGroup, MenuItemGroupPropsType } from '../XMenuItemGroup'
  import { XMenuItem, MenuItemPropsType } from '../XMenuItem'
  import { MenuPropsType } from './types'

  defineOptions({
    name: 'XMenu'
  })

  const props = withDefaults(defineProps<MenuPropsType>(), {
    ellipsis: false,
    options: [] as any,
    border: false,
    selectHandler: () => {},
    openHandler: () => {},
    closeHandler: () => {}
  })

  const elMenuRef = ref()
  defineExpose(
    new Proxy(
      {},
      {
        get: (target, key) => elMenuRef.value?.[key],
        has: (target, key) => key in elMenuRef.value
      }
    )
  )

  const borderStyle = computed(() => {
    if (StrUtil.isStr(props.border)) return props.border
    return props.border ? '' : 'none'
  })
</script>

<template>
  <el-menu
    ref="elMenuRef"
    class="x-menu"
    :style="{ border: borderStyle }"
    :mode="mode"
    :collapse="collapse"
    :ellipsis="ellipsis"
    :ellipsis-icon="ellipsisIcon"
    :popper-offset="popperOffset"
    :default-active="defaultActive"
    :default-openeds="defaultOpeneds"
    :unique-opened="uniqueOpened"
    :router="router"
    :collapse-transition="collapseTransition"
    :popper-effect="popperEffect"
    :close-on-click-outside="closeOnClickOutside"
    :popper-class="popperClass"
    :show-timeout="showTimeout"
    :hide-timeout="hideTimeout"
    :background-color="backgroundColor"
    :text-color="textColor"
    :active-text-color="activeTextColor"
    @select="selectHandler"
    @open="openHandler"
    @close="closeHandler"
  >
    <slot :collapse="collapse">
      <template v-if="options.length > 0">
        <template v-for="(item, index) in options" :key="index">
          <x-sub-menu
            v-if="item.type === MenuTypeConst.SUB_MENU"
            v-bind="{ ...item, teleported: true, collapse } as SubMenuPropsType"
          />
          <x-menu-item-group
            v-if="item.type === MenuTypeConst.MENU_ITEM_GROUP"
            v-bind="item as MenuItemGroupPropsType"
          />
          <x-menu-item
            v-if="item.type === MenuTypeConst.MENU_ITEM"
            v-bind="{ ...item, collapse } as MenuItemPropsType"
          />
        </template>
      </template>
    </slot>
  </el-menu>
</template>

<style lang="scss">
  @use './style' as *;
</style>
